package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.LoginFormDTO;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import com.hmdp.mapper.UserMapper;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RegexUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.PriorityBlockingQueue;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.*;
import static com.hmdp.utils.SystemConstants.USER_NICK_NAME_PREFIX;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {



    @Resource
    private StringRedisTemplate stringRedisTemplate;


    //发送验证码功能实现
    @Override
    public Result sendCode(String phone, HttpSession session) {

        //校验手机号的格式
        if(RegexUtils.isPhoneInvalid(phone))
        {
            //不符合
            return Result.fail("手机号格式错误");
        }

        //符合，生成对应的验证码
        String code = RandomUtil.randomNumbers(6);

        //TODO 将验证码存入Redis
//        session.setAttribute("code",code);
        stringRedisTemplate.opsForValue().set(LOGIN_CODE_KEY+phone,code);

        //发送验证码
        log.debug("验证码为：code="+code);

        //返回ok

        return Result.ok();
    }

    //实现用户短信登录功能
    @Override
    public Result login(LoginFormDTO loginForm, HttpSession session) {

        String phone = loginForm.getPhone();

        //每次请求前检验手机号的校验
        if(RegexUtils.isPhoneInvalid(phone))
        {
            return Result.fail("手机号格式有误！");
        }
        //校验验证码
        //TODO 获取Redis缓存中的用户验证码
//        Object chaseCode = session.getAttribute("code");
        String chaseCode = stringRedisTemplate.opsForValue().get(LOGIN_CODE_KEY+phone);
        //获取当前登录用户的验证码
        String code = loginForm.getCode();

        if(chaseCode==null||!(chaseCode.equals(code)))
        {
            //不一致报错
            return Result.fail("验证码有误！");
        }


        //一致根据手机号查询用户
        User user = query().eq("phone",phone).one();


        if(user==null)
        {
            //不存在，创建用户并保存
            user =createUserWithPhone(phone);

        }


        //TODO 保存用户信息的Redis中

        //1.创建Token作为key
        String token = UUID.randomUUID().toString(true);
        //2.属性拷贝
        UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
        //将userDTO转为map集合批量存储到Redis中(将id long类型转为String)
        Map<String, Object> map = BeanUtil.beanToMap(userDTO,new HashMap<>(),
                CopyOptions.create()
                        .setIgnoreNullValue(true)
                        .setFieldValueEditor((fieldName,fieldValue)->fieldValue.toString()));
        //保存用户信息的Redis中
        stringRedisTemplate.opsForHash().putAll(LOGIN_USER_KEY+token,map);
        //设置token的有效期
        stringRedisTemplate.expire(LOGIN_USER_KEY+token,LOGIN_USER_TTL, TimeUnit.MINUTES);

//        session.setAttribute("user", BeanUtil.copyProperties(user, UserDTO.class));


        return Result.ok(token);
    }

    private User createUserWithPhone(String phone) {

        User user=new User();

        //存入手机号
        user.setPhone(phone);

        //存入用户名
        String name=USER_NICK_NAME_PREFIX+RandomUtil.randomString(10);
        user.setNickName(name);

        //将用户信息添加到数据中
        save(user);

        return user;
    }
}
